<%@page language="java" contentType="text/html; charset=UTF-8" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="html" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<html:header title="零售收银">
    <link rel="stylesheet" href="${baseUrl}css/public.css" media="all">

    <style>
        a{
            color: #01AAED;
            text-decoration: none;
            font-size: 12px;
        }
        a:hover {
            cursor: pointer;
            color: #FF5722;
        }

        .layui-input{
            font-size: 16px;
            border-color:#cccccc;
        }
        .layui-input:focus{border-color:#4287cf!important}

        .header{
            overflow: hidden;
            background-color: #3e424d;width: 100%; height: 76px;
        }

        .header-button{
             float: left;background-color: #4f535e;height: 76px;color: #FFFFFF;padding: 14px 10px 18px 10px;margin-left: 2px;
         }
        .header-button:hover{
            background-color: #4287cf;
            cursor: pointer;
        }

        .titleLog{
            float: left;padding-left:10px;height:76px;line-height:76px;color: #FFFFFF;font-size: 30px;font-weight: bold;font-style: italic;letter-spacing:5px;
        }

        .vertical-line{
            float: left;background-color: #FFFFFF;width: 1px;height: 40px;margin:18px 10px;
        }



        .content-goods{
            margin: 0px 10px 0 10px;background-color: #FFFFFF;overflow-y: auto;min-height: 642px;
        }

        .content-goods table{
            margin-top: 0px;
        }

        .content-goods thead th{
            font-size: 16px;
            font-weight: bold;
            text-align: left;
        }

        .content-goods thead tr{
            background-color: #FFFFFF;
        }

        .content-goods tbody td{
            font-size: 14px;
            text-align: left;
        }

        .total-goods{
            overflow: hidden;
            width: 100%;
            background-color: #FFFFFF;
            height: 60px;
            line-height: 60px;
            border-top: 1px #aaaaaa solid;
            border-bottom: 1px #aaaaaa solid;
        }

        .bottom-div{
            height: 158px;
            margin:0;
            padding:0;
        }

        .input-div{
            display: inline-block;position: relative;
        }

        .input-div .button-icon {
            position: absolute;top: 0px;right: 0px; height: 38px;width: 40px;
            border-left: 1px #cccccc solid;
        }

        .input-div .button-icon:hover {
            background-color: #1E9FFF;
            cursor: pointer;
        }

        .input-div .button-icon i{
            color: #666;
            font-size: 22px;width: 40px;text-align: center; height: 38px;line-height: 38px;
        }
        .input-div .button-icon:hover i{
            color: #FFFFFF;
        }


        .settle-div{
            height: 158px;
        }
        .settle-div:hover{
            cursor: pointer;
            background-color: #ffeeb9;
        }

        .sn-button:hover{
            background-color: #FF5722;
            cursor: pointer;
        }
    </style>

    <script>
        let houseId = '${retailSetVo.houseId}';
        let goodsList = [];
        let existHang = isTrue("${exist}");
        jQuery(function () {
            $(window).focus();

            if (existHang) {
                $("#hasHang").css("display","inline-block");
            }

            $("#total-number").html(0);
            $("#total-amount").html(getPrice(0));
            $("#final-amount").html(getPrice(0));

            $(".barcode-input").focus();

            $(".barcode-input").keypress(function (e) {
                if (e.which == 13) {
                    let temp = $(this).val();
                    selectGoods(temp);
                    $(this).val('');
                }
            });

            $(".custom-input").keypress(function (e) {
                if (e.which == 13) {
                    selectCustom();
                    $(this).val('');
                }
            });


            $(".discount-input").bind("input propertychange", function(){
                discountInputProcess($(this).val());
            });
        });

        /**
         * 窗口能否被关闭
         * */
        function cancelAble() {
            if ($('iframe').attr("src") == "${baseUrl}sale/retail/lock.action"){
                return false;
            }

            if ($('iframe').attr("src") == "${baseUrl}sale/retail/noSetTip.action"){
                return false;
            }

            return true;
        }

        function closeAllDialog(){
            $(window).focus();
            $(".barcode-input").focus();
            closeAll();

            console.log("main closeAllDialog");
        }

        function discountInputProcess(input){
            if (input == "") {
                input = 0;
            } else {
                input = parseFloat(input);
                if (input < 0) {
                    input = -input;
                }
            }

            let data = getFormJson($("form"));
            if (data.discountFlag == '2') {
                if (input > parseFloat($("#total-amount").html())) {
                    errTip("折扣金额不能大于总金额");
                    input = 0;
                }

                $(this).val(getPrice(input));
            } else {

                $(this).val(getNumber(input));
            }

            processTotal();
        }

        layui.use(['form', 'table', 'laydate'], function () {
            let $ = layui.jquery,
                form = layui.form,
                table = layui.table,
                laydate = layui.laydate,
                util = layui.util;


            if ("${noSet}" == "1") {
                openNoSetDialog();
            }

            if (_login_user.retailStatus == 2){
                //锁定状态
                openLockDialog();
            }

            form.on('select(discountFlag)', function (data) {
                if (data.value == '1'){
                    $(".discount-input").val(100);
                    $("#discount-icon").html("%");
                } else {
                    $(".discount-input").val(getPrice(0));
                    $("#discount-icon").html("元");
                }

                processTotal();
            });



            window.addEventListener("keydown", function(e) {
                console.log("keyCode:"+ e.keyCode);


                if (!cancelAble() && (e.keyCode != 0x0D)) {
                    //如果是不能关闭的窗口在显示，则不能响应快捷键
                    return;
                }
                if (e.keyCode == 0x1B){//取消
                    if (cancelAble()) {
                        closeAllDialog();
                    }
                }else if (e.keyCode == 0x0D && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {//ctrl+enter
                    if ($('.layui-layer-content iframe')[0]!=undefined && $('.layui-layer-content iframe')[0].length!=0){
                        var iframe = window[$('iframe')[0]['name']];
                        if (iframe.CtrlEnter != undefined) {
                            console.log("零售页面调用shiftEnter");
                            iframe.CtrlEnter();
                        }
                    }
                    CtrlEnter();
                } else if (0x0D == e.keyCode && e.shiftKey) {
                    if ($('.layui-layer-content iframe')[0]!=undefined && $('.layui-layer-content iframe')[0].length!=0){
                        var iframe = window[$('iframe')[0]['name']];
                        if (iframe.shiftEnter != undefined) {
                            console.log("零售页面调用shiftEnter");
                            iframe.shiftEnter();
                        }
                    }
                } else if (e.keyCode == 39){
                    if ($('.layui-layer-content iframe')[0]!=undefined && $('.layui-layer-content iframe')[0].length!=0){
                        var iframe = window[$('iframe')[0]['name']];
                        if (iframe.right != undefined) {
                            console.log("零售页面调用right");
                            iframe.right();
                        }
                    }
                }  else if (e.keyCode == 37){

                    if ($('.layui-layer-content iframe')[0]!=undefined && $('.layui-layer-content iframe')[0].length!=0){
                        var iframe = window[$('iframe')[0]['name']];
                        if (iframe.left != undefined) {
                            console.log("零售页面调用left");
                            iframe.left();
                        }
                    }
                } else if (e.keyCode == 0x0D){//确认
                    if ($('.layui-layer-content iframe')[0]!=undefined && $('.layui-layer-content iframe')[0].length!=0){
                        var iframe = window[$('iframe')[0]['name']];
                        if (iframe.enter != undefined) {
                            console.log("零售页面调用enter");
                            iframe.enter();
                        }
                    }
                } else if (e.keyCode == 38){
                    if ($('.layui-layer-content iframe')[0]!=undefined && $('.layui-layer-content iframe')[0].length!=0){
                        var iframe = window[$('iframe')[0]['name']];
                        if (iframe.up != undefined) {
                            console.log("零售页面调用up");
                            iframe.up();
                        }
                    } else {
                        up();
                    }

                    e.preventDefault();
                } else if (e.keyCode == 40){
                    if ($('.layui-layer-content iframe')[0]!=undefined && $('.layui-layer-content iframe')[0].length!=0){
                        var iframe = window[$('iframe')[0]['name']];
                        if (iframe.down != undefined) {
                            console.log("零售页面调用up");
                            iframe.down();
                        }
                    } else {
                        down();
                    }
                    e.preventDefault();
                } else if (e.keyCode == 89 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {//ctrl+Y
                    if ($('.layui-layer-content iframe')[0]!=undefined && $('.layui-layer-content iframe')[0].length!=0){
                        var iframe = window[$('iframe')[0]['name']];
                        if (iframe.ctrlY != undefined) {
                            console.log("零售页面调用ctrlY");
                            iframe.ctrlY();
                        }
                    } else {
                        ctrlY();
                    }
                }  else if (e.keyCode == 113 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {//ctrl+f2
                    if ($('.layui-layer-content iframe')[0]!=undefined && $('.layui-layer-content iframe')[0].length!=0){
                        var iframe = window[$('iframe')[0]['name']];
                        if (iframe.ctrlF2 != undefined) {
                            console.log("零售页面调用ctrlF2");
                            iframe.ctrlF2();
                        }
                    }
                } else if (e.keyCode == 114 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {//ctrl+f3
                    if ($('.layui-layer-content iframe')[0]!=undefined && $('.layui-layer-content iframe')[0].length!=0){
                        var iframe = window[$('iframe')[0]['name']];
                        if (iframe.ctrlF3 != undefined) {
                            console.log("零售页面调用ctrlF3");
                            iframe.ctrlF3();
                        }
                    }
                }  else if (e.keyCode == 0x76 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {//ctrl+f7
                    help();
                } else if (e.keyCode == 118){
                    changeGoods();
                } else if (e.keyCode == 121){//F10
                    printLast();
                }  else if (e.keyCode == 0x77){//F8
                    hang();
                } else if (e.keyCode == 0x78){//F9
                    take();
                } else if (e.keyCode == 0x7B && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {//ctrl+f12
                    lock();
                } else if (e.keyCode == 0x51 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {//ctrl+Q
                    $(".barcode-input").focus();
                } else if (e.keyCode == 0x49 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {//ctrl+I
                    $(".discount-input").focus().select();
                } else if (e.keyCode == 112 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {//ctrl+F1
                    $(".custom-input").focus();
                } else if (e.keyCode == 46 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {//ctrl+F1
                    deleteAllGoods();
                } else if (46 == e.keyCode && e.shiftKey) {
                    clearPage();
                } else if (e.keyCode == 46) {//F8
                    deleteGoods();
                }
            }, false);


            util.event('lay-active', {
                help: function(){
                    help();
                },
                hang:function () {
                    hang();
                },
                take:function () {
                    take();
                },
                lock:function () {
                    lock();
                },
                screen:function () {
                    screen();
                },
                selectGoods:function () {
                    selectGoods($(".barcode-input").val());
                },
                selectCustom:function () {
                    selectCustom();
                },
                deleteGoods:function () {
                    deleteGoods();
                },
                printLast:function () {
                    printLast();
                },
                sett:function () {
                    CtrlEnter();
                }
            });
        });

        function CtrlEnter() {
            if (goodsList.length == 0) {
                errTip("请选择商品");
                return;
            }

            //检查商品
            let flag = false;
            $.each(goodsList,function (i,d) {
                if (d.packetId == undefined && d.sn) {
                    if (d.goodsSnList==undefined || d.goodsSnList.length==0){
                        errTip("商品["+d.name+"]的序列号未选择");
                        flag = true;
                        return false;
                    } else if (d.goodsSnList.length != d.number){
                        errTip("商品["+d.name+"]的序列号个数和数量不一致，请重新选择");
                        flag = true;
                        return false;
                    }
                }
            });
            if (flag){
                return;;
            }


            openDialog("${baseUrl}sale/retail/sett.action", "单据结算", ['780px','520px'], function (layero, index) {
                var iframe = window[layero.find('.layui-layer-content iframe')[0]['name']];
                iframe.setAmount(parseFloat($("#final-amount").html()));
            });

        }
        
        function changeGoods() {
            openDialog("${baseUrl}sale/retail/changeGoods.action", null, ['780px','520px'], function (layero, index) {
                var iframe = window[layero.find('.layui-layer-content iframe')[0]['name']];
                let vo = goodsList[current_selected_index-1];
                if (vo.packetId == undefined) {
                    let usedNumber = goods_number_map[vo.id] == undefined ? 0:goods_number_map[vo.id]-vo.number*vo.times ;
                    let stockNum = vo.baseStockNum==null ? 0:vo.baseStockNum-usedNumber;
                    vo.stockNum = stockNum/ vo.times;
                } else {
                    vo.stockNum = genPacketStockWithUsed(vo,goods_number_map) + vo.number;
                }
                iframe.setGoodsData(vo,houseId,goodsSn_map);
            });
        }

        function clearPage() {
            current_selected_index = 1;
            goods_number_map = {};
            goodsSn_map = {};
            deleteAllGoods();
            $("form")[0].reset();
            $("#discount-icon").html('%');
            $("#custom-name").html('');
            $('[name="customId"]').val("${retailSetVo.customId}");
            $("#total-number").html(0);
            $("#total-amount").html(getPrice(0));
            $("#final-amount").html(getPrice(0));
            $("#custom-name").html("${retailSetVo.custom.name}");
        }
        
        function deleteAllGoods() {
            goodsList=[];
            renderListDiv();
        }

        function deleteGoods() {
            let index = current_selected_index-1;
            goodsList.splice(index,1);
            renderListDiv();

            if (current_selected_index>=max_data_length){
                current_selected_index=max_data_length;
            }
            current_selected_index = current_selected_index==0 ? 1:current_selected_index;
            selectedLine(current_selected_index);
        }

        function printLast() {
            get("${baseUrl}sale/retail/getLastOrder.action", function (res) {
                if (res.code == 1){
                    console.log(res.data);
                    document.getElementById("printFrame").contentWindow.printPage(res.data);
                } else {
                    errTip(res.msg);
                }
            });
        }

        function selectGoods(search) {
            get("${baseUrl}sale/retail/getRetailGoodsVoList?houseId="+houseId+"&page=1&limit=10&search="+search, function (res) {
               if (res.code == 0){
                   if (res.data.length == 0) {
                       getSelectGoods(null);
                   } else if (res.data.length == 1){
                       let d = res.data[0];
                       let vo;
                       if (d.type == 2) {
                           vo = d.packetVo;
                           vo.packetId = d.packetVo.id;
                           vo.stockNum = genPacketStockWithUsed(d.packetVo,goods_number_map);
                       }else{
                           vo = d.goodsVo;
                           vo.goodsId = d.goodsVo.id;
                           vo.unitId = d.goodsVo.goodsUnitVoList[0].unitId;
                           vo.price = d.goodsVo.goodsUnitVoList[0].retailPrice;
                           vo.times = d.goodsVo.goodsUnitVoList[0].times;
                           let usedNumber = goods_number_map[d.goodsVo.id] == undefined ? 0:goods_number_map[d.goodsVo.id] ;
                           let stockNum = d.goodsVo.baseStockNum==null ? 0:d.goodsVo.baseStockNum-usedNumber;
                           vo.stockNum = stockNum/ vo.times;
                       }

                       if (vo.stockNum == null || vo.stockNum==0) {
                           errTip("库存不足");
                           return;
                       }

                       let number = 1;
                       if (vo.stockNum < 1){
                           number = vo.stockNum;
                       }

                       vo.number = number;
                       vo.amount = number*vo.price;
                       getSelectGoods(vo);
                   } else {
                       openDialog("${baseUrl}sale/retail/selectGoods.action?houseId="+houseId+"&search="+search,"选择商品",undefined,function (layero, index) {
                           var iframe = window[layero.find('.layui-layer-content iframe')[0]['name']];
                           iframe.setUsedMap(goods_number_map);
                       });
                   }
               } else {
                   errTip(res.msg);
               }
            });


        }


        function selectCustom() {
            let search = $(".custom-input").val();
            get("${baseUrl}custom/custom/getList?status=1&page=1&limit=10&search="+search, function (res) {
                if (res.code == 0) {
                    if (res.data.length == 0) {
                        getSelectCustom(null);
                    }else if (res.data.length == 1){
                        getSelectCustom(res.data[0]);
                    } else {
                        openDialog("${baseUrl}sale/retail/selectCustom.action?search="+search,"选择客户");
                    }
                }
            });


        }
        
        function screen() {
            let $screen = $("#screen");
            if ($screen.attr("status") == 'normal') {
                fullScreen();
                $screen.find("i").removeClass("fa-window-maximize");
                $screen.find("i").addClass("fa-window-restore");
                $screen.attr("status","full");
                $screen.find("#screenTip").html("退出全屏");
            } else {
                exitFullScreen();
                $screen.find("i").removeClass("fa-window-restore");
                $screen.find("i").addClass("fa-window-maximize");
                $screen.attr("status","normal");
                $screen.find("#screenTip").html("全屏");
            }
        }

        function ctrlY() {
            snGoodsJson = JSON.parse($(".layui-table tr[index='" + current_selected_index + "']").attr("data"));
            snGoodsJson.index = current_selected_index;
            if (snGoodsJson.goodsId!=null && snGoodsJson.sn){
                openDialog("${baseUrl}sale/retail/selectSn.action?houseId="+houseId+"&goodsId="+snGoodsJson.goodsId,"选择序列号",['780px','520px'],function (layero, index) {
                    var iframe = window[layero.find('.layui-layer-content iframe')[0]['name']];
                    if (snGoodsJson.goodsSnList!=undefined && snGoodsJson.goodsSnList.length > 0) {
                        iframe.setGoodsSnList(snGoodsJson.goodsSnList);
                    }

                    if (goodsSn_map[snGoodsJson.goodsId]!=undefined && goodsSn_map[snGoodsJson.goodsId].length > 0) {
                        iframe.setUsedSnList(goodsSn_map[snGoodsJson.goodsId]);
                    }
                });
            }
        }

        function help() {
            openDialog("${baseUrl}sale/retail/hotKeyHelp.action","快捷键帮助");
        }

        function lock() {
            post("${baseUrl}sale/retail/lockRetail.action",{},function (res) {
                if (res.code == 1){
                    openLockDialog();
                } else {
                    errTip(res.msg);
                }
            });
        }

        function hang() {
            if (goodsList.length == 0) {
                errTip("未选择商品");
                return;
            }

            openDialog("${baseUrl}sale/retail/hang.action", undefined,['500px','300px'],function(layero, index){
                var iframe = window[layero.find('.layui-layer-content iframe')[0]['name']];
                let data = getFormJson($("form"));
                iframe.setGoodsList(goodsList,data.customId, data.discountFlag, data.discountInput);
            });
        }

        function take() {
            if (!existHang) {
                errTip("您还没有挂单");
                return;
            }

            if (goodsList.length == 0) {
                //2.有挂单，且未选择商品， 直接提取 挂的单据
                takeProcess(null);
            } else {
                //3.有挂单，且选择商品，确认框提示
                openDialog("${baseUrl}sale/retail/take.action", undefined,['500px','300px']);

            }


        }

        function takeProcess(userHangVo) {
            let flag = 1;
            if (userHangVo == null) {
                flag = 2;
                userHangVo = {};
            }
            post("${baseUrl}sale/retail/takeGoods.action", userHangVo, function (res) {
                if (res.code == 1) {
                    if (flag == 2){
                        existHang = false;//不存在挂单
                        $("#hasHang").css("display","none");
                    }

                    clearPage();
                    let userHangVo = res.data;
                    if (userHangVo.discountFlag == 1) {
                        userHangVo.discountInput = userHangVo.discountRate;
                    } else {
                        userHangVo.discountInput = getPrice(userHangVo.discountAmt);
                    }
                    formSetVal("form",userHangVo);
                    $("#custom-name").html(userHangVo.custom.name);

                    let tip = '';
                    $.each(userHangVo.userHangGoodsVoList, function (i,d) {

                        let vo;
                        if (d.packetVo != null) {
                            vo = d.packetVo;
                            vo.packetId = d.packetVo.id;
                            vo.number = d.number;
                            vo.price = d.price;
                            vo.amount = d.amount;
                            vo.remark = d.remark;
                            vo.stockNum = genPacketStockWithUsed(d.packetVo,goods_number_map);
                        }else{
                            vo = d.goodsVo;
                            vo.goodsId = d.goodsVo.id;
                            vo.unitId = d.unitId;
                            vo.times = d.times;
                            vo.number = d.number;
                            vo.price = d.price;
                            vo.amount = d.amount;
                            vo.remark = d.remark;
                            let usedNumber = goods_number_map[d.goodsVo.id] == undefined ? 0:goods_number_map[d.goodsVo.id] ;
                            let stockNum = d.goodsVo.baseStockNum==null ? 0:d.goodsVo.baseStockNum-usedNumber;
                            vo.stockNum = stockNum/ vo.times;
                            if (vo.goodsSnList==null || vo.goodsSnList.length==0) {
                                vo.goodsSnList = undefined;
                            }

                            if (vo.sn) {
                                //开启序列号的，还需要判断挂单的序列号是否已经被使用了
                                if (vo.goodsSnList==undefined || vo.number != vo.goodsSnList.length){
                                    tip += vo.name + "、";
                                }
                            }
                        }
                        goodsList.push(vo);
                    });
                    if (tip != ''){
                        tip = tip.substring(0,tip.length-1);
                        errTip("["+tip+"]挂单的序列号有被使用了，请重新选择序列号");
                    }

                    renderListDiv();
                } else {
                    errTip(res.msg);
                }
            });
        }

        function openDialog(url, title, area,process) {
            let config = {
                title: false,
                type: 2,
                shade: 0.6,
                area: ['700px', '520px'],
                maxmin:false,
                shadeClose: false,
                content: url,
                success: function(layero, index){
                    if (process != undefined){
                        process(layero, index);
                    }
                },
            };

            if (title!=undefined) {
                config.title = [title, 'font-size:18px;font-weight:bold;'];
            }

            if (area != undefined) {
                config.area = area;
            }

            let index = layer.open(config);
        }

        function openLockDialog() {
            let config = {
                title: false,
                type: 2,
                shade: 0.6,
                closeBtn: 0,
                area: ['500px', '300px'],
                maxmin:false,
                shadeClose: false,
                content: "${baseUrl}sale/retail/lock.action",
            };

            let index = layer.open(config);
        }

        function openNoSetDialog() {
            let config = {
                title: false,
                type: 2,
                shade: 0.6,
                closeBtn: 0,
                area: ['500px', '300px'],
                maxmin:false,
                shadeClose: false,
                content: "${baseUrl}sale/retail/noSetTip.action",
            };

            let index = layer.open(config);
        }

        let current_selected_index = 1;
        let max_data_length = 0;
        function up() {
            if (current_selected_index<=1){
                current_selected_index=1;
            } else {
                current_selected_index--;
            }

            selectedLine(current_selected_index);
        }

        function down() {
            if (current_selected_index>=max_data_length){
                current_selected_index=max_data_length;
            } else {
                current_selected_index++;
            }
            selectedLine(current_selected_index);
        }
        function selectedLine(index) {
            let $parent = $("#goodsList");
            $(".layui-table tr").css("background-color","#ffffff");
            $(".layui-table tr[index='" + index + "']").css("background-color","#ffeeb9");

            let $this = $(".layui-table tr[index='" + index + "']");
            $parent.animate({
                scrollTop: $this.offset().top-$this.height() - $parent.offset().top + $parent.scrollTop()
            },200);
        }

        function clickGoodsContent(index) {
            current_selected_index = index;
            selectedLine(current_selected_index);
        }

        function getGoodsTr(item) {
            let child='<tr class="goods-tr" index="'+item.index+'" data=\''+JSON.stringify(item)+'\' onclick="clickGoodsContent('+item.index+');">\n' +
                '                <td>'+item.index+'</td>\n';
            if(item.packetId == undefined){
                let snChild = '';
                if (item.sn) {
                    snChild = '<span class="layui-badge layui-bg-blue sn-button">sn</span>';
                }
                let goodsUnitVo = genUnitVo(item.goodsUnitVoList,item.unitId);
                child += '                <td>'+goodsUnitVo.code+'</td>\n' +
                    '                <td>'+genGoodsName(item.name,item.norms)+'</td>\n' +
                    '                <td>'+goodsUnitVo.unit.name+'</td>\n' +
                    '                <td>'+getNumber(item.number)+snChild+'</td>\n' +
                    '                <td>'+getPrice(item.price)+'</td>\n' +
                    '                <td>'+getPrice(item.amount)+'</td>\n' +
                    '                <td></td>\n';
            } else {
                child += '                <td></td>\n' +
                    '                <td>'+item.name+'</td>\n' +
                    '                <td></td>\n' +
                    '                <td>'+getNumber(item.number)+'</td>\n' +
                    '                <td>'+getPrice(item.price)+'</td>\n' +
                    '                <td>'+getPrice(item.amount)+'</td>\n' +
                    '                <td></td>\n';
            }
            child += '            </tr>';

            return child;
        }

        function getSelectCustom(data) {
            $(window).focus();
            $('.barcode-input').focus();
            if (data == null) {
                errTip("未找到客户");
                return;
            }
            $("#custom-name").html(data.name);
            $('[name="customId"]').val(data.id);
        }

        /**
         * 如果使用商品选择窗口，必须实现此函数，否则取不到已选择的商品数据
         * @param data
         */
        function getSelectGoods(data) {
            $(window).focus();
            $('.barcode-input').focus();
            if (data == null) {
                errTip("未找到商品");
                return;
            }

            if (data.goodsId!=null && data.sn) {
                snGoodsJson=data;
                snGoodsJson.index = max_data_length+1;
                openDialog("${baseUrl}sale/retail/selectSn.action?houseId="+houseId+"&goodsId="+data.goodsId,"选择序列号",['780px','520px'], function (layero, index) {
                    var iframe = window[layero.find('.layui-layer-content iframe')[0]['name']];
                    if (goodsSn_map[snGoodsJson.goodsId]!=undefined && goodsSn_map[snGoodsJson.goodsId].length > 0) {
                        iframe.setUsedSnList(goodsSn_map[snGoodsJson.goodsId]);
                    }
                });
            } else {
                goodsList.push(data);
                renderListDiv();
                current_selected_index = max_data_length;
                selectedLine(current_selected_index);
            }
        }

        let snGoodsJson;
        /**
         * 如果使用sn选择窗口，必须实现此函数，否则取不到已选择的序列号
         * @param data
         */
        function getSelectSnList(snList) {
            $(window).focus();
            $('.barcode-input').focus();
            if (snList.length == 0) {
                return;
            }

            snGoodsJson.goodsSnList = snList;
            snGoodsJson.number = snList.length;
            snGoodsJson.amount = snGoodsJson.number*snGoodsJson.price;


            let $this = $(".layui-table tr[index='" + snGoodsJson.index + "']");
            if ($this.length == 0) {
                goodsList.push(snGoodsJson);
                renderListDiv();
                current_selected_index = max_data_length;
                selectedLine(current_selected_index);
            } else {
                goodsList[snGoodsJson.index-1]=snGoodsJson;
                renderListDiv();
            }

            processTotal();
        }

        /**
         * 用于goodsid  goodsSnList
         * @type {{}}
         */
        let goodsSn_map = {};

        /**
         * goodsId goodsNumber 商品的基本单位的数量
         * @type {{}}
         */
        let goods_number_map = {};
        function renderListDiv() {
            goods_number_map = {};
            goodsSn_map = {};
            $("#goodsList").empty();
            $.each(goodsList, function (i,item) {
                item.index = i+1;
                $("#goodsList").append(getGoodsTr(item));

                if (item.packetId == undefined){
                    let number = item.number * item.times;
                    if (goods_number_map[item.goodsId] == undefined) {
                        goods_number_map[item.goodsId] = number;
                    } else {
                        goods_number_map[item.goodsId] = goods_number_map[item.goodsId]+number;
                    }

                    if (item.sn) {
                        if (goodsSn_map[item.goodsId] == undefined){
                            goodsSn_map[item.goodsId] = [];
                        }

                        $.each(item.goodsSnList, function (i,d) {
                            goodsSn_map[item.goodsId].push(d);
                        });
                    }
                } else {
                    //套餐处理
                    let packetNumber = item.number;
                    $.each(item.packetGoodsVoList,function (i,d) {
                        let number = packetNumber*d.number * d.times;
                        if (goods_number_map[d.goodsId] == undefined) {
                            goods_number_map[d.goodsId] = number;
                        } else {
                            goods_number_map[d.goodsId] = goods_number_map[d.goodsId]+number;
                        }
                    });
                }
            });

            max_data_length = goodsList.length;
            if (current_selected_index < max_data_length) {
                current_selected_index = max_data_length;
            }

            current_selected_index = current_selected_index==0 ? 1:current_selected_index;
            if (max_data_length > 0) {
                selectedLine(current_selected_index);
            }
            processTotal();
            $(".sn-button").unbind().bind("click",function () {
                current_selected_index = parseInt($(this).parents("tr.goods-tr").attr("index"));
                selectedLine(current_selected_index);
                ctrlY();
            });
        }


        /**
         * 如果使用商品数量修改，必须实现此函数，否则取不到已修改的信息
         * @param data
         */
        function getChangeData(data) {
            $(window).focus();
            $('.barcode-input').focus();
            data.index = current_selected_index;
            goodsList[current_selected_index-1] = data;
            renderListDiv();
            processTotal();
        }



        /**
         *
         * 挂单成功，供子页面调用
         * */
        function hangSuccess() {
            $(window).focus();
            $('.barcode-input').focus();
            existHang = true;
            clearPage();
            $("#hasHang").css("display","inline-block");
        }

        function takeCallBack(type) {
            $(window).focus();
            $('.barcode-input').focus();
            if (type==1 && goodsList.length > 0){
                let data = getFormJson($("form"));
                //调取换单
                let userHangVo = {};
                userHangVo.customId = data.customId;
                userHangVo.discountFlag = data.discountFlag;
                if (userHangVo.discountFlag == "1") {
                    userHangVo.discountRate = data.discountInput;
                } else {
                    userHangVo.discountAmt = data.discountInput;
                }

                let userHangGoodsList = [];
                let userHangSnList = [];
                $.each(goodsList,function (i,d) {
                    let vo = {};
                    vo.goodsId = d.goodsId;
                    vo.packetId = d.packetId;
                    vo.unitId = d.unitId;
                    vo.times = d.times;
                    vo.price = d.price;
                    vo.number = d.number;
                    vo.amount = d.amount;
                    vo.remark = d.remark;
                    userHangGoodsList.push(vo);
                    if (d.goodsSnList != undefined && d.goodsSnList.length > 0){
                        $.each(d.goodsSnList, function (j, goodsSn) {
                            userHangSnList.push({goodsId:goodsSn.goodsId,goodsSnId:goodsSn.id});
                        });
                    }
                });

                userHangVo.userHangGoodsList = userHangGoodsList;
                userHangVo.userHangSnList = userHangSnList;

                takeProcess(userHangVo);
            } else {
                //直接取单
                takeProcess(null);
            }
        }


        /**
         * 如果使用结算窗口，必须实现此函数，否则取不到已修改的信息
         * @param data
         */
        function settOrder(settAccountId) {
            $(window).focus();
            $('.barcode-input').focus();
            let data = getFormJson($("form"));
            let sale = {};
            sale.settAccountId = settAccountId;
            sale.customId = data.customId;
            sale.houseId = data.houseId;
            sale.discountFlag = data.discountFlag;
            if (sale.discountFlag == "1") {
                sale.discountRate = data.discountInput;
            } else {
                sale.discountAmt = data.discountInput;
            }
            sale.totalAmt = $("#final-amount").html();

            let saleGoodsVoList = [];
            let salePacketVoList = [];
            $.each(goodsList,function (i,d) {
                if (!emptyEntity(d.goodsId)) {
                    let vo = {};
                    vo.goodsId = d.goodsId;
                    vo.unitId = d.unitId;
                    vo.times = d.times;
                    vo.number = d.number;
                    vo.price = d.price;
                    vo.amount = d.amount;
                    vo.remark = d.remark;
                    vo.goodsSnList = [];
                    $.each(d.goodsSnList,function (i,goodsSn) {
                        delete goodsSn.index;
                        vo.goodsSnList.push(goodsSn);
                    });
                    saleGoodsVoList.push(vo);
                } else {
                    let vo = {};
                    vo.packetId = d.packetId;
                    vo.packetName = d.name;
                    vo.packetNo = d.no;
                    vo.number = d.number;
                    vo.price = d.price;
                    vo.amount = d.amount;
                    vo.remark = d.remark;

                    let packetGoodsVoList = [];
                    $.each(d.packetGoodsVoList,function (i,pg) {
                        packetGoodsVoList.push({
                            packetId : pg.packetId,
                            goodsId : pg.goodsId,
                            unitId:pg.unitId,
                            times:pg.times,
                            number:pg.number,
                            price:pg.price,
                            amount:pg.amount,
                        });
                    });

                    vo.packetGoodsVoList = packetGoodsVoList;
                    salePacketVoList.push(vo);
                }
            });

            sale.saleGoodsVoList = saleGoodsVoList;
            sale.salePacketVoList = salePacketVoList;

            post("${baseUrl}sale/retail/addSale.action", sale, function (res) {
                closeAll();
                if (res.code == 1) {
                    tip("结算成功");
                    clearPage();
                } else {
                    errTip(res.msg);
                }
            });
        }

        function processTotal() {
            let number=0;
            let amount=0;
            $.each(goodsList, function (i, item) {
                number += item.number;
                amount += item.amount;
            });

            $("#total-number").html(getNumber(number));
            $("#total-amount").html(getPrice(amount));

            let data = getFormJson($("form"));
            let discount_input = parseFloat($(".discount-input").val());
            if (discount_input > amount && data.discountFlag == '2') {
                $(".discount-input").val(getPrice(0));
                discount_input = 0;
            }


            if (data.discountFlag == '1') {
                let rate=discount_input/100;
                $("#final-amount").html(getPrice(rate*amount));
            } else {
                $("#final-amount").html(getPrice(amount-discount_input));
            }
        }
    </script>
</html:header>
<iframe id="printFrame" style="width:0px;height:0px" src="${baseUrl}print/salePrint.action" frameborder="0"></iframe>
<body style="width: 100%;min-width: 900px;height:100%;margin: 0;padding:0;background-color: #eeeeee;overflow: auto;">

<form class="layui-form" style="width: 100%;height:100%;" lay-filter="form">
    <input type="hidden" name="customId" value="${retailSetVo.customId}">
    <input type="hidden" name="houseId" value="${retailSetVo.houseId}">
    <input type="hidden" name="userId" value="${userVo.id}">
    <input type="hidden" name="retail" value="true">

    <div class="header">
        <div class="titleLog">零售收银</div>

        <div class="vertical-line"></div>

        <div style="float: left;color: #FFFFFF;padding: 18px 0;">
            <div style="font-size: 18px;">${company.name}</div>
            <div style="font-size: 12px;" id="userName">${userVo.name}</div>
        </div>

        <div class="vertical-line"></div>

        <div style="float: left;color: #FFFFFF;padding: 18px 0;">
            <div style="font-size: 16px;">${retailSetVo.house.name}</div>
            <div style="font-size: 12px;" id="storeName">${retailSetVo.store.name}</div>
        </div>

        <div style="float: right;">
            <div class="header-button" lay-active="lock">
                <div style="text-align: center">
                    <i class="fa fa-lock" style="font-size: 24px;"></i>
                </div>
                <div style="font-size: 16px;text-align: center">
                    锁屏(Ctrl+F12)
                </div>
            </div>


            <div class="header-button" lay-active="hang">
                <div style="text-align: center">
                    <i class="fa fa-calendar-plus-o" style="font-size: 24px;"></i>
                </div>
                <div style="font-size: 16px;text-align: center">
                    挂单(F8)
                </div>
            </div>


            <div class="header-button" lay-active="take">
                <div style="text-align: center">
                    <i class="fa fa-calendar-minus-o" style="font-size: 24px;"></i>
                    <span id="hasHang" class="layui-badge-dot" style="display: none;"></span>
                </div>
                <div style="font-size: 16px;text-align: center">
                    取单(F9)
                </div>
            </div>

            <div class="header-button" lay-active="help">
                <div style="text-align: center">
                    <i class="fa fa-keyboard-o" style="font-size: 24px;"></i>
                </div>
                <div style="font-size: 16px;text-align: center">
                    快捷键帮助(Ctrl+F7)
                </div>
            </div>
        </div>
        <div style="clear: both;"></div>
    </div>
    <div class="content-goods">
        <table class="layui-table" lay-skin="line" lay-size="lg">
            <colgroup>
                <col width="5%">
                <col width="8%">
                <col width="20%">
                <col width="5%">
                <col width="9%">
                <col width="10%">
                <col width="10%">
                <col width="14%">
                <col width="10%">
                <col width="8%">
                <col>
            </colgroup>

            <thead>
            <tr>
                <th>序号</th>
                <th>条形码</th>
                <th>商品名称/规格</th>
                <th>单位</th>
                <th>数量</th>
                <th>单价(元)</th>
                <th>金额(元)</th>
                <th>备注</th>
            </tr>
            </thead>

            <tbody id="goodsList">
            </tbody>
        </table>
    </div>


    <div class="total-goods">
        <div style="float: left; margin-left: 20px;">
            <span style="font-size: 16px;color: #999;">
                数量：<span id="total-number" style="font-size: 18px;color: #666;font-weight: bold;">0</span>件
            </span>

            <span style="font-size: 16px;color: #999;margin-left: 20px">
                合计金额：<span id="total-amount" style="font-size: 18px;color: #666;font-weight: bold;">0.00</span>元
            </span>
        </div>

        <div style="float: right;margin-right: 20px;">
            <a href="#" lay-active="printLast" style="font-size: 16px;border-right:1px #aaaaaa solid;padding-right: 20px;">打印上一单(F10)</a>
            <a href="#" lay-active="deleteGoods" style="font-size: 16px; padding-left: 20px;">删除商品(Delete)</a>
        </div>
    </div>
    <div class="bottom-div">

        <div class="layui-row">
            <div class="layui-col-xs7" style="height:158px;border-right: 1px solid #cccccc;">
                <div style="margin: 32px 20px 0 20px;">
                    <div class="input-div barcode-div" style="width: 49%">
                        <input class="layui-input barcode-input" placeholder="扫描条形码（Ctrl+Q）" style="padding-right: 60px;color: #666;">
                        <div class="button-icon" lay-active="selectGoods">
                            <i class="fa fa-shopping-bag" ></i>
                        </div>
                    </div>

                    <div class="input-div" style="position: relative;width: 49%;">
                        <input type="number" name="discountInput" class="layui-input discount-input" value="100" style="color: #666;padding-left: 100px;padding-right: 50px;">
                        <div style="position: absolute;top: 0;left: 0;width: 96px;">
                            <select name="discountFlag" lay-filter="discountFlag">
                                <option value="1">折扣率</option>
                                <option value="2">折扣额</option>
                            </select>
                        </div>
                        <div class="button-icon">
                            <i id="discount-icon" style="font-size: 18px;padding-left: 10px;font-weight: bold;">%</i>
                        </div>
                    </div>
                </div>

                <div style="margin: 20px 20px 0 20px;">
                    <div class="input-div" style="width: 49%">
                        <input class="layui-input custom-input" placeholder="选择客户（Ctrl+F1）" style="padding-right: 60px; color: #666;">
                        <div class="button-icon" lay-active="selectCustom">
                            <i class="fa fa-address-book"></i>
                        </div>
                    </div>

                    <div class="input-div" style="width: 49%;">
                        <div style="border: 1px solid #cccccc;height: 36px;line-height: 36px;padding: 0 10px;color: #666;font-size: 16px;">
                            <i class="fa fa-user"></i>
                            <span style="padding-right: 6px;">客户名称</span>
                            <span id="custom-name" style="padding-left: 10px;border-left: 1px solid #bbbbbb;height: 36px;line-height: 36px;">${retailSetVo.custom.name}</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="layui-col-xs5 settle-div" lay-active="sett">
                <div style="float: left;font-size: 40px;font-weight: bold;color: #666;height: 158px;line-height: 158px;padding-left: 80px;">
                    结算
                </div>
                <div style="float: right; padding: 32px 40px 0 40px;">
                    <div style="color:#666;font-size: 20px;text-align: right;">
                        总计金额
                    </div>

                    <div style="color:#FFB800;font-size: 40px;font-weight: bold;padding-top: 20px;">
                        ￥<span id="final-amount">0.00</span>
                    </div>
                </div>
            </div>
        </div>

    </div>
</form>
</body>

</html>